var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
const cors = require('cors') //导入跨域请求模块
// 服务端校验Token
var { jwtAuth } = require('./jwt')

var indexRouter = require('./routes/index')
var categorysRouter = require('./routes/categorys')
var articlesRouter = require('./routes/articles')
var commentsRouter = require('./routes/comments')
var usersRouter = require('./routes/users')
var messagesRouter = require('./routes/messages')
var uploadRouter = require('./routes/upload')
var downloadRouter = require('./routes/download')
var loginRouter = require('./routes/login')

var app = express()

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use(cors()) // 挂载跨域请求中间件
app.use(jwtAuth) // 服务端校验Token
// 使用全局错误处理中间件，捕获解析 JWT 失败后产生的错误
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.send({
      code: 401,
      msg: 'invalid token...',
    })
    // res.status(401).send('invalid token...')
  }
  res.send({
    status: 500,
    message: '未知错误',
  })
})

app.use('/', indexRouter)
app.use('/categorys', categorysRouter) // 导入分类路由模块
app.use('/articles', articlesRouter) // 导入文章路由模块
app.use('/comments', commentsRouter) // 导入评论路由模块
app.use('/users', usersRouter) // 导入用户路由模块
app.use('/messages', messagesRouter) // 导入留言路由模块
app.use('/upload', uploadRouter) // 上传路由模块
app.use('/download', downloadRouter) // 下载路由模块
app.use('/login', loginRouter) // 导入登陆验证 ( token验证 ) 模块

module.exports = app
